<template>
  <div class="app-container">

    <el-form :model="queryParams.domain" ref="queryForm" v-show="showSearch" :inline="true" @submit.native.prevent>
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="queryParams.domain.roleName" placeholder="请输入角色名称" clearable size="small" style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="权限标识" prop="roleKey" :show-overflow-tooltip="true" width="200" />
      <el-table-column label="创建时间" prop="createTime" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="角色级别" prop="roleLevel" :show-overflow-tooltip="true" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:role:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限标识" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    listRole,
    getRole,
    delRole,
    addRole,
    updateRole,
    roleTreeSelect,
    exportRole,
    changeRoleStatus
  } from "@/api/system/role";



  export default {
    name: "Role",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 角色表格数据
        roleList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openRolwScope: false,
        // 日期范围
        // dateRange: [],
        statusOptions: [],
        menuExpand: false,
        menuNodeAll: false,
        menuOptions: [],
        //菜单树选中的ID
        menuIdList: [],
        modelOptions:[],
        // 查询参数
        queryParams: {
          domain: {
            roleName: ""
          },
          pageNum: 1,
          pageSize: 10,
          sortName: "",
          sortOrder: ""
        },
        menuQuery:{

          roleId:undefined
        },
        // 表单参数
        form: {},
        hasCheckedMenuIdList:[],
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          roleName: [
            { required: true, message: "角色名称不能为空", trigger: "blur" },
            { max: 20, message: "角色名称长度最大为20", trigger: "blur" },
            { pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]{0,}$/, message: "只能包含汉字、字母、数字、-、_", trigger: "blur" }
          ],
          roleKey: [
            { required: true, message: "权限标识不能为空", trigger: "blur" },
            { min: 4, message: "权限标识长度最小为4", trigger: "blur" },
            { max: 20, message: "权限标识长度最大为20", trigger: "blur" },
            { pattern: /^[a-zA-Z0-9_-]{0,}$/, message: "只能包含字母、数字、-、_", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();

    },
    methods: {
       async modelChange(value){
         let templist = this.getSelectedNodes();
         this.hasCheckedMenuIdList = this.hasCheckedMenuIdList.concat(templist);
         console.log("加载的菜单个数："+this.hasCheckedMenuIdList.length);
        await this.getMenuTreeselect();
        await this.setValue(this.menuIdList);
      },

      /** 查询角色列表 */
      getList() {
        this.loading = true;
        listRole(this.queryParams).then(
          response => {
            this.roleList = response.data.records;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.roleId)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      cancelMenuScope() {
        this.openRolwScope = false;
        this.reset();
      },

      // 表单重置
      reset() {
        this.menuQuery={
          roleId:undefined
        }
         this.hasCheckedMenuIdList = [];
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.form = {
          roleName: undefined,
          roleKey: undefined,
          remark: undefined,
        };
        this.resetForm("form");

      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        // this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 查询菜单树结构 */
      async getMenuTreeselect() {
        await roleTreeSelect(this.menuQuery).then(response => {
          this.menuOptions = response.data.menuTree;
          this.menuIdList = response.data.menuIdList;
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加角色";
        this.getMenuTreeselect();
      },
      /** 修改按钮操作 */
      async handleUpdate(row) {
          this.reset();
          this.open = true;
          this.title = "修改角色";
          this.form = JSON.parse(JSON.stringify(row))
          this.menuQuery.roleId = row.roleId;
          await this.getMenuTreeselect();
          await this.setValue(this.menuIdList)

      },
      // 菜单回显  row为角色拥有的菜单ID集合
      setValue(row){
        let _this = this;
        _this.$data.thisRefTree = setInterval(() =>{
          row.forEach((i) => {
            let node = _this.$refs.menu.getNode(i);
            if(node.isLeaf){
              _this.$refs.menu.setChecked(node, true);
            }
          });
          clearInterval(_this.$data.thisRefTree)
        },0)
      },

      //获取到选中的节点
      getSelectedNodes() {
        // 目前被选中的菜单节点
        let list = this.$refs.menu.getCheckedKeys()
        console.log('===list1',list);
        let list2 = this.$refs.menu.getHalfCheckedKeys()
        console.log('===list2',list);
        list2.forEach(i => {
          list.push(i)
        })
        return list;
      },
      /** 提交按钮 */
      submitForm: function() {
         this.loading = true;
        this.form.menuIdList = this.hasCheckedMenuIdList.concat(this.getSelectedNodes());
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.roleId != undefined) {
              updateRole(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                 this.loading = false;
              });
            } else {
              addRole(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                 this.loading = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const roleIds = row.roleId || this.ids;
        this.$confirm('是否确认删除角色"' + row.roleName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delRole(roleIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
        if (type == 'menu') {
          let treeList = this.menuOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
          }
        } else if (type == 'dept') {
          let treeList = this.deptOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
          }
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
        if (type == 'menu') {
          this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
        } else if (type == 'dept') {
          this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
        }
      },


    }
  };
</script>
